package pers.karl.design.basic.strategy.xx.strategy;

import pers.karl.design.basic.strategy.xx.XXStrategy;
import pers.karl.design.basic.strategy.xx.XXStrategyType;

import java.util.HashMap;
import java.util.Map;

/**
 * 策略工厂
 *
 *    放入工厂类的方式：
 *      主动存入： 策略类中添加存入方法、
 *      被动：包扫描等有其他管理者负责将数据存入
 *
 *    由于调用方是通过枚举类获取策略实现类的，通过工厂的意义感觉并不大~
 *
 * @author karl
 */
public class XXStrategyFactory {

    private static final XXStrategyFactory xxStrategyFactory = new XXStrategyFactory();

    static {
        xxStrategyFactory.register(XXStrategyType.ONE, new OneXXStrategy());
        xxStrategyFactory.register(XXStrategyType.TWO, new TwoXXStrategy());
    }

    private XXStrategyFactory() {
    }

    public static XXStrategyFactory getInstance() {
        return xxStrategyFactory;
    }

    private Map<XXStrategyType, XXStrategy> strategies = new HashMap<>();

    /**
     * 将策略加入到集合中，避免后期增加策略时，需要修改工厂类
     * @param strategyType
     * @param strategy
     */
    private void register(XXStrategyType strategyType, XXStrategy strategy){
        if(strategyType == null) {
            throw new IllegalArgumentException("strategyType is null");
        }
        if(strategy == null) {
            throw new IllegalArgumentException("strategy is null");
        }

        strategies.put(strategyType,strategy);
    }

    /**
     * 获取策略对象
     * @param strategyType
     * @return
     */
    public XXStrategy getStrategy(XXStrategyType strategyType){
        return strategies.get(strategyType);
    }

}
